﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace chapter1._6Web.Modules
{
    public class UrlRewrite : IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += AppBeginRequest;
        }

        private void AppBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            //获取当前访问的原始url
            var url = app.Request.RawUrl;
            //\w代表匹配的规则是字母开头,\d代表数字
            Regex reg = new Regex(@"\w+_\d+\.html");
            if (reg.IsMatch(url))
            {
                //detail_1.html
                //从后往前获取_的下标
                int hIndex = url.LastIndexOf("_");//6
                //从后往前获取.的下标
                int portIndex = url.LastIndexOf(".");//8
                //Substring(开始下标,截取个数)，截取出id  1
                int id = int.Parse(url.Substring(hIndex + 1, portIndex - hIndex - 1));
                //将id拼接到真实的url地址
                string reactUrl = "~/detail.aspx?id=" + id;
                //终止当前的url请求转到指定的url请求
                app.Server.Transfer(reactUrl);
            }
        }
    }
}